import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import Result from "@/common/utils/result.util";

/**
 * Note[过滤器]
 * @Catch() 捕获所有异常, @Catch(HttpException) 只捕获 HttpException 异常
 * 当局部存在多个异常过滤器时，例如存在多个全局异常过滤器时，具体由 异常的构造函数 决定匹配哪个过滤器
 * 例如存在@Catch(Error)[等效于@Catch()], @Catch(HttpException), 不论注册顺序如何
 * HttpException 被 @Catch(HttpException) 捕获而不会被 @Catch(Error) 捕获
 * 即便 Error 是 HttpException 的父类
 */

/** 匹配所有异常并格式化返回 */
@Catch()
export class BaseExceptionFilter implements ExceptionFilter {
    catch(exception: Error, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        if (exception instanceof HttpException) {
            const { message, statusCode }: { message: string | string[]; statusCode: number } =
                exception.getResponse() as any;
            response
                .status(statusCode)
                .json(Result.exception(Array.isArray(message) ? message.join(", ") : message, statusCode));
        } else {
            const status = HttpStatus.INTERNAL_SERVER_ERROR;
            response.status(status).json(Result.exception(exception.message, status));
        }
    }
}
